package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.service.LendReturnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 还款记录表 前端控制器
 * </p>
 *
 * @author Bright
 * @since 2022-04-09
 */
@Slf4j
@RestController
@Api(tags = "还款计划")
@RequestMapping("/api/core/lendReturn")
public class LendReturnController {
    @Resource
    LendReturnService lendReturnService;


    @ApiOperation(value = "得到还款计划列表")
    @GetMapping("/list/{lendId}")
    public R list(
            @ApiParam(value = "标的id", required = true)
            @PathVariable Long lendId) {

        return R.ok().data("list", lendReturnService.listByLendId(lendId));
    }

    @ApiOperation(value = "得到用户的还款计划表")
    @GetMapping("/listAll")
    public R listAll(HttpServletRequest request) {
        return null;
    }

    @ApiOperation(value = "还款")
    @PostMapping("/auth/commitReturn/{lendReturnId}")
    public R commitReturn(@PathVariable Long lendReturnId, HttpServletRequest request) {
        String token = request.getHeader("token");
        Assert.isTrue(JwtUtils.checkToken(token), ResponseEnum.LOGIN_AUTH_ERROR);
        Long userId = JwtUtils.getUserId(token);

        return R.ok().data("formStr", lendReturnService.commitReturn(lendReturnId, userId));

    }

    @ApiOperation(value = "还款异步回调")
    @PostMapping("/notify")
    public String notifyReturn(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("还款异步回调：" + JSON.toJSONString(paramMap));
        String resultCode = paramMap.get("resultCode").toString();

        if (HfbConst.SUCCESSCODE.equals(resultCode)) {

            if (RequestHelper.isSignEquals(paramMap)) {

                return lendReturnService.notifyReturn(paramMap);
            } else {
                log.info("异步回调签名失败......");
                return "fail";
            }
        } else {
            log.info("异步回调失败.......");
            return "fail";
        }
    }

}
